package dao;

import tool.Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GroupMessageDao {
    Util util = new Util();
    Connection con = null;

    public void insertGroupMessage(String groupName, String content, String username) {
        con = util.getConnection();
        String sql = "insert into group_message(name, username, message) values (?,?,?)";
        try {
            PreparedStatement preparedStatement = con.prepareStatement(sql);
            preparedStatement.setString(1, groupName);
            preparedStatement.setString(2, username);
            preparedStatement.setString(3, content);
            preparedStatement.execute();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public String[] getGroupMessages(String name) {
        con = util.getConnection();
        List<String> list = new ArrayList<>();
        String sql = "select * from group_message where name=? and status=0";
        try {
            PreparedStatement preparedStatement = con.prepareStatement(sql);
            preparedStatement.setString(1, name);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                String string1 = resultSet.getString("username");
                String string2 = resultSet.getString("message");
                String string = string1 + ":" + string2;
                list.add(string);
            }
            return list.toArray(new String[0]);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}